package com.mmall.Concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
public class SemaphoreExample1 {
    private final static int threadCount = 200;

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(20); //并发数
        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            executorService.execute(()->{
                try{
                    semaphore.acquire();   //获得许可
                    test(threadNum);
                    semaphore.release();  //释放许可
                }catch (Exception e){
                    log.info("exception",e);
                }finally {
                    //保证肯定执行

                }
            });
        }

        log.info("finish");
        executorService.shutdown();
    }

    private static void test(int num) throws Exception{
        log.info("{}",num);
        Thread.sleep(1000);
    }
}
